import { join } from 'path';
import * as fs from 'fs';

/**
 * Configuration factory that loads and merges configuration from different sources
 * Priority (highest to lowest):
 * 1. Environment variables
 * 2. Environment-specific .env file (.env.{NODE_ENV}.local)
 * 3. Environment-specific .env file (.env.{NODE_ENV})
 * 4. Local .env file (.env.local)
 * 5. Default .env file (.env)
 * 6. Default configuration values
 */
export const configFactory = () => {
  const environment = process.env.NODE_ENV || 'development';

  // Load environment-specific configuration
  const environmentConfig = loadEnvironmentConfig(environment);

  // Default configuration values
  const defaultConfig = {
    app: {
      name: process.env.APP_NAME || 'nest-ai-tools',
      port: parseInt(process.env.PORT || '3000', 10),
      environment,
    },
    database: {
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT || '5432', 10),
      username: process.env.DB_USERNAME || 'postgres',
      password: process.env.DB_PASSWORD || 'postgres',
      database: process.env.DB_NAME || 'nest_ai_tools',
    },
    ai: {
      anthropic: {
        apiKey: process.env.ANTHROPIC_API_KEY || '',
      },
      openai: {
        apiKey: process.env.OPENAI_API_KEY || '',
      },
      deepseek: {
        apiKey: process.env.DEEPSEEK_API_KEY || '',
      },
      openrouter: {
        apiKey: process.env.OPENROUTER_API_KEY || '',
      },
      // Add other AI model configurations as needed
    },
  };

  // Merge configurations with environment-specific taking precedence
  return { ...defaultConfig, ...environmentConfig };
};

/**
 * Load environment-specific configuration from a JSON file if it exists
 * @param environment The current environment (development, production, test, etc.)
 */
function loadEnvironmentConfig(environment: string): Record<string, any> {
  const configPath = join(process.cwd(), 'config', `${environment}.json`);

  try {
    if (fs.existsSync(configPath)) {
      const configContent = fs.readFileSync(configPath, 'utf8');
      return JSON.parse(configContent) as Record<string, any>;
    }
  } catch (error) {
    console.warn(
      `Failed to load config file for environment ${environment}:`,
      error,
    );
  }

  return {};
}
